package stuttgart.uni.bluetoothcontactexchange;

import java.io.IOException;
import java.io.ObjectInputStream;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class ContactExchangeClient extends Service {
	Thread clientThread;
	
	private BluetoothAdapter btAdapter;
	private BluetoothDevice btDevice;
	private BluetoothSocket btSocket;
	private ObjectInputStream btIn;
	
	private boolean sendSuccessful = false;
	
	private synchronized void setSendSuccessful(){
		sendSuccessful=true;
	}
	
	private synchronized boolean getSendSuccessful(){
		return sendSuccessful;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d("ClientService","im onStart");
		Log.d("ClientService","inside onStartCommand");
		clientThread = new ClientThread(intent.getExtras().getString("SERVER_MAC_ADDRESS"));
		clientThread.start();
		
		return START_NOT_STICKY;
	}
	
	private class ClientThread extends Thread{
		
		
		private String serverMacAddress;
		
		public ClientThread(String serverMacAddress) {
			this.serverMacAddress = serverMacAddress;
		}
		

		public void run() {
			// Netwerk 
			Log.d("ClientService","im run");
			PersonData personData = null;
			
			btAdapter = BluetoothAdapter.getDefaultAdapter() ;
			Log.d("ClientService","btadapter erstellt");
			btDevice = btAdapter.getRemoteDevice(serverMacAddress);
			Log.d("ClientService","device erstellt");
			
			
			try {
				// Netwerk Verbindungsaufbau
				btSocket = btDevice.createRfcommSocketToServiceRecord(ContactExchangeServer.btCoExUUID);
				btSocket.connect();
				Log.d("ClientService","verbunden");
			} catch (IOException e) {
				Log.d("ClientService","Error creating Socket");
			}
			
			try {
				// Erstellt Inputstream
				btIn = new ObjectInputStream(btSocket.getInputStream());
				Log.d("ClientService","input stream erstellt");
			} catch (IOException e) {
				Log.d("ClientService","Error getting Sockets InputStream");
			}
			
			try {
				// Datenuebertragung
				personData = (PersonData) btIn.readObject();
				Log.d("ClientService","daten gelesen");
			} catch (IOException e) {
				Log.d("ClientService","Error reading Person Data");
			} catch (ClassNotFoundException e) {
				Log.d("ClientService","Error reading Person Data ClassNotFound");
			}
			
			try {
				// Stream und Sockets werden geschlossen
				close();
				Log.d("ClientService","close");
			} catch (IOException e) {
				Log.d("ClientService","Error closing Connection");
			}
			
			if(personData!=null){
				ContactData cdb = new ContactData(getContentResolver());
				
				try {
					// Daten abspeichern
					cdb.saveContact(personData);
					setSendSuccessful();
				} catch (RemoteException e) {
					Log.d("ClientService","RemoteException saving Contact");
					e.printStackTrace();
				} catch (OperationApplicationException e) {
					Log.d("ClientService","OperationApplicationException saving Contact");
					e.printStackTrace();
				}
				
			}
			stopSelf();
		}
	}
	
	private void close() throws IOException{
		if(btIn!=null){
			btIn.close();
		}
		if(btSocket!=null){
			btSocket.close();
		}
	}
	
	@Override
	public void onDestroy() {
		if(getSendSuccessful()){
			// Erfolgsmeldung Ausgabe
			Toast.makeText(getApplicationContext(),"Kontakt erfolgreich empfangen", Toast.LENGTH_LONG).show();
		}
		else{
			// Miserfolg Ausgabe
			Toast.makeText(getApplicationContext(),"Kontakt empfangen fehlgeschlagen", Toast.LENGTH_LONG).show();
		}
		
		try {
			close();
		} catch (IOException e) {
			Log.d("ServerService","Error closing Connection");;
		}
		super.onDestroy();
	}
	
	@Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
